using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

namespace Elvex
{
    public class MessageBoxRequest
    {
        public event Action<MessageBoxRequest, int> Clicked;

        internal void OnClicked(int btnid)
        {
            if (null != Clicked)
            {
                Clicked(this, btnid);
            }
        }
    }

    public class MessageBoxButtonData
    {
        public string Name { get; }

        public MessageBoxButtonData(string name)
        {
            Name = name;
        }
    }


    public static class MessageBox
    {
        private class Configuration
        {
            public GameObject Prefab { get; private set; }

            public Type ViewType { get; private set; }

            public Configuration(string asset, Type viewtype)
            {
                Prefab = Assets.Load<GameObject>(asset);
                ViewType = viewtype;
            }
        }

        private static Configuration m_configuration = null;

        public static void Configure(string asset, Type viewtype)
        {
            m_configuration = new Configuration(asset, viewtype);
        }

        public static MessageBoxRequest Show(Transform parent, string title, string text, params MessageBoxButtonData[] buttons)
        {
            if(null ==  m_configuration )
            {
                return null;
            }

            var req = new MessageBoxRequest();
            GameObject go = UnityEngine.Object.Instantiate(m_configuration.Prefab, parent);
            var model = go.GetComponent<MessageBoxModel>();
            if (null == model) model = go.AddComponent<MessageBoxModel>();
            model.SetData(title, text, buttons, btn => { req.OnClicked(btn); });

            var view = go.GetComponent(m_configuration.ViewType);
            if (null == view) view = go.AddComponent(m_configuration.ViewType);

            var controller = go.GetComponent<MessageBoxController>();
            if (null == controller) controller = go.AddComponent<MessageBoxController>();

            return req;
        }
    }
}
